package com.woniuxy.handler;

import com.alibaba.fastjson.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.woniuxy.mapper.GoodsMapper;
import com.woniuxy.other.PictureAudit;
import com.woniuxy.rabbitmq.RabbitMQSend;
import com.woniuxy.service.GoodsService;
import com.woniuxy.service.GoodsShowService;
import com.woniuxy.util.TimeUtils;
import com.work.framework.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author fengyao
 * @version 1.0
 * @date 2019/9/17 0017 上午 11:12
 */
@Controller
@Api(value = "卖家模块商品管理",tags = "卖家模块")
@EnableSwagger2
@EnableCaching
@RequestMapping("/seller")
public class SellerGoodsHandler {

    @Resource
    GoodsShowService goodsShowService;

    @Resource
    GoodsService goodsService;

    @Resource
    RabbitMQSend rabbitMQSend;

    @PostMapping("/addGoods")
    @ApiOperation("商品上传功能")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品详情信息",name = "goods",required = true,dataType = "Goods",paramType = "path")
    })
    public ModelAndView addGoods(Goods goods, Auction auction, @RequestParam("myPictures") MultipartFile[] myPictures, HttpSession session){

        System.out.println("商品信息："+goods);
        System.out.println("图片信息："+myPictures[0]);
        System.out.println("拍卖信息："+auction);
        try {
            //用户的登录状态判断
            User user= (User) session.getAttribute("user");
            System.out.println(user);
            if(user==null){
              return new ModelAndView("redirect:http://192.168.40.21:8080/web-view/login.html");
            }

            System.out.println("通过用户校验："+user);

            //后台基本验证
            HashMap error=new HashMap<String,String>();
            if(myPictures.length==0){
                error.put("pictureError","图片内容为null");
            }
            if(goods.getGname()==null&&"".equals(goods.getGname())){
                error.put("gnameError","商品名字为null");
            }else if(goods.getGname().length()<2 ||goods.getGname().length()>10){
                error.put("gnameError","名称小于10");
            }
//            后期与前台一致
            //图片转化为二进制流
            System.out.println(goods);
            byte[] fbytes = myPictures[0].getBytes();
            // 图片审核
            boolean b = PictureAudit.pictureAudit(fbytes);
            if(b==false){
                //违禁，将状态修改为0
                auction.setStatus(1);
                System.out.println("图片违禁");
            }else {auction.setStatus(3);}
            if(!error.isEmpty()){
                //将错误信息存储到session
                session.setAttribute("error",error);
                //重定向到put页面
                System.out.println("发生错误，跳回去");
                return new ModelAndView("redirect:http://localhost:8131/putaway.html");
            }
            //定义图片名称
            String newFileName = UUID.randomUUID().toString().replace("-", "");
            String originalFilename = myPictures[0].getOriginalFilename();
            System.out.println("originalFilename"+originalFilename);
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String realName=newFileName+suffix;

            //将图片上传到nginx，并取得可以访问的地址
            String dirPath="F:/nginx-1.17.4/html/img/products";
            String uploadPath=dirPath+realName;
            System.out.println(uploadPath);
            String path="img/products/"+realName;
            BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(uploadPath));
            bufferedOutputStream.write(fbytes);
            bufferedOutputStream.flush();

            //取得uid
            //商品本身上传
            goods.setUid(1);
            goodsService.insertGoods(goods);
            Integer gid=goods.getGid();
            //竞拍信息
            auction.setGid(gid);
            auction.setCreated(TimeUtils.getCreated());
            auction.setStart(TimeUtils.getStartTime());
            auction.setStop(TimeUtils.getStopTime());
            goodsService.insertAuction(auction);
            //图片信息
            Picture picture=new Picture();
            picture.setGid(gid);
            picture.setUrl(path);
            picture.setStatus(0);
            goodsService.insertPicture(picture);
            Thread thread = new Thread(){
                @Override
                public void run() {
                    try {
                        Long time1=TimeUtils.getTimeDiff(auction.getStart(),auction.getCreated())-30*60000;
                        rabbitMQSend.sendCollect(auction.getAid(), (long) (1000*30));
                        //2.时间达到开始时间时，修改商品状态
                        Long time2=TimeUtils.getTimeDiff(auction.getStart(),auction.getCreated());
                        rabbitMQSend.sendStart(gid,auction.getAid(),(long) (1000*60));
                        //3.时间到达结束时间时，修改状态
                        Long time3=TimeUtils.getTimeDiff(auction.getStop(),auction.getCreated());
                        rabbitMQSend.sendStop(auction.getAid(),(long) (1000*120));
                        System.out.println("执行1");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
            System.out.println("执行3");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("执行2");
        return new ModelAndView("redirect:http://192.168.40.21:8080/web-view/login.html");
    }

    @GetMapping("/test")
    @ApiOperation("test")
    public void test(HttpSession session,HttpServletRequest request){
        System.out.println(request.getSession().getId());
        System.out.println("session中取："+session.getAttribute("user"));
        System.out.println("request中取："+request.getSession().getAttribute("user"));
    }
    /**
     * 我的拍卖品
     * @param session 获取用户信息
     * @return 返回结果
     */
    @ResponseBody
    @GetMapping("/myGoods")
    @ApiOperation("返回我的拍卖品")
    public ResultDTO selectMyGoods(HttpSession session){
//        User user= (User) session.getAttribute("user");
        List<GoodsAuctionDTO> goodsAuctionDTOS = goodsShowService.selectGoodsMyGoods(1);
        return new ResultDTO(200,"成功",goodsAuctionDTOS);
    }

    @ResponseBody
    @GetMapping("/soldOut/{gid}")
    @ApiOperation("下架商品")
    @ApiImplicitParam(value = "商品id",name = "id",paramType = "Integer")
    public ResultDTO soldOutGoods(@PathVariable Integer gid){
        goodsService.updateAuctionValid(gid);
        return new ResultDTO(200,"成功",null);
    }
}
